var render,gameObject;

var readGameObject = function (file,onFinish)
{
    var reader = new FileReader();
    reader.onload = function(e) {
        var fileString = e.target.result;
        if(file.name.search(/.*\.obj$/) != -1) 
            go = Engine.ObjReader(fileString);
        else
            go = Engine.AscReader(fileString);
    	onFinish(go);
    };
    reader.onerror = function(e) {
        alert("Do not open this HTML file in file system, ");
    };
    reader.readAsText(file);
}

var readTexture = function (file,onFinish)
{ 
    var reader = new FileReader();
    reader.onload = function(blob) {
       texture = new Engine.Texture(new Uint8Array(blob.target.result));
       onFinish(texture);
    };
    reader.onerror = function(e) {
        alert("Do not open this HTML file in file system, ");
    };
    reader.readAsArrayBuffer(file);
}

var getValue = function (id)
{
    return parseFloat($("#"+id).val());
}

var setValue = function (id, value)
{
    return $("#"+id).val(value);
}

var initCameraView = function(){
    setValue("cpx",render.scene.camera.position.x);
    setValue("cpy",render.scene.camera.position.y);
    setValue("cpz",render.scene.camera.position.z);
    setValue("lax",render.scene.camera.lookat.x);
    setValue("lay",render.scene.camera.lookat.y);
    setValue("laz",render.scene.camera.lookat.z);
    setValue("wux",render.scene.camera.worldup.x);
    setValue("wuy",render.scene.camera.worldup.y);
    setValue("wuz",render.scene.camera.worldup.z);
    setValue("fov",render.scene.camera.FOV);
}

var updateCamera = function(){
    render.scene.camera.position.x = getValue("cpx");
    render.scene.camera.position.y = getValue("cpy");
    render.scene.camera.position.z = getValue("cpz");

    render.scene.camera.lookat.x = getValue("lax");
    render.scene.camera.lookat.y = getValue("lay");
    render.scene.camera.lookat.z = getValue("laz");
    
    render.scene.camera.worldup.x = getValue("wux");
    render.scene.camera.worldup.y = getValue("wuy");
    render.scene.camera.worldup.z = getValue("wuz");
    
    render.scene.camera.FOV = getValue("fov");
}

var initGameObjectView = function(){
    if(!gameObject)
        return;
    setValue("px",gameObject.transform.position.x);
    setValue("py",gameObject.transform.position.y);
    setValue("pz",gameObject.transform.position.z);
    
    setValue("sx",gameObject.transform.scale.x);
    setValue("sy",gameObject.transform.scale.y);
    setValue("sz",gameObject.transform.scale.z);
    
    setValue("rx",gameObject.transform.rotation.x);
    setValue("ry",gameObject.transform.rotation.y);
    setValue("rz",gameObject.transform.rotation.z);
    
    setValue("ksr",gameObject.shader.ks.r);
    setValue("ksg",gameObject.shader.ks.g);
    setValue("ksb",gameObject.shader.ks.b);
    
    setValue("kar",gameObject.shader.ka.r);
    setValue("kag",gameObject.shader.ka.g);
    setValue("kab",gameObject.shader.ka.b);

    setValue("kdr",gameObject.shader.kd.r);
    setValue("kdg",gameObject.shader.kd.g);
    setValue("kdb",gameObject.shader.kd.b);
    
    setValue("ns",gameObject.shader.s);
    
    if(gameObject.shader.textureName)
        $("#textureName").text(gameObject.shader.textureName);
    else
        $("#textureName").text("No Texture");
    $("#textureFile").val("");
    
    if(gameObject.shader.type)
        $("#shaderType").val(gameObject.shader.type);
    else
        $("#shaderType").val("phong");
}

var updateGameObject = function(){
    if(!gameObject)
        return;
    gameObject.transform.position = new Engine.Vector3(getValue("px"),getValue("py"),getValue("pz"));
    gameObject.transform.scale = new Engine.Vector3(getValue("sx"),getValue("sy"),getValue("sz"));
    gameObject.transform.rotation = new Engine.Vector3(getValue("rx"),getValue("ry"),getValue("rz"));
    
    gameObject.shader.ks = {
        r: getValue("ksr"),
        g: getValue("ksg"),
        b: getValue("ksb")
    };

    gameObject.shader.ka = {
        r: getValue("kar"),
        g: getValue("kag"),
        b: getValue("kab")
    };
    
    gameObject.shader.kd = {
        r: getValue("kdr"),
        g: getValue("kdg"),
        b: getValue("kdb")
    };
    
    gameObject.shader.s = getValue("ns");
    gameObject.shader.type = $("#shaderType").val();
}

var updateFrame = function ()
{
    if(!render)
        return;
	
    updateGameObject();
    updateCamera();
    
    render.begin();
    render.draw();
    
	var canvas = new Engine.Canvas("main",render.width,render.height);
	render.flush(canvas);
}

window.onload = function() {
    
/*	
	for(var r = 0; r <=255;r++)
	{
		for(var g=0;g<=255;g++)
		{
			for(var b = 0;b<=255;b++)
			{
				//var a = getToonColor(r,g,b,3,2);
				//var q = a.r;
				//var w = a.g;
				//var e = a.b;
				//getHue(r,g,b);
			}
		}
	}

*/	

	//var a = getToonColor(5,5,5,3,2);
	
	//alert(a.r + " " + a.g + " " + a.b);
//	var h = getHue(5,5,5);
	
//	alert(h);
	render = new Engine.Render(256,256);
	initCameraView();
    window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem || mozRequestFileSystem;
    
    $("#resetCamera").on("click",function(evt){
        setValue("cpx",0);
        setValue("cpy",5);
        setValue("cpz",-5);
        setValue("lax",0);
        setValue("lay",0);
        setValue("laz",0);
        setValue("wux",0);
        setValue("wuy",1);
        setValue("wuz",0);
        setValue("fov",63.7);
        updateFrame();
    });
    
    $("input:file").css("width","120px");
    
    $("#textureButton").on("click", function(event ){
        var file = $("#textureFile")[0].files[0];
        if(!file){
            alert("Please select texture file first");
            return;
        }
        readTexture(file,function(t){
            if(gameObject)
            {
                gameObject.shader.texture = t;
                gameObject.shader.textureName = file.name;
                $("#textureName").text(gameObject.shader.textureName);
                updateFrame();
            }
            else
            {
                alert("Please select gameObject first");
            }
        });
        
    });
    
    $("#importModel").on("click",function(event) {
        var file = $("#modelFile")[0].files[0];
        if(!file){
            alert("Please select model file first");
            return;
        }
        
        readGameObject(file,function(go){
            go.name = file.name;
            render.scene.addGameObject(go);
            updateFrame();
            $("#gameObjectList").append($("<option></option>").attr("value",go.id).text(go.name));
            if($("#gameObjectList option:selected")[0])
                $("#gameObjectList option:selected")[0].selected = false;
            $("#gameObjectList option")[$("#gameObjectList option").length-1].selected = true;
            $('#gameObjectList').trigger('change');
        });
    });
    
    $("#deleteModel").on("click",   function(event) {
        var ids = $("#gameObjectList").val();
        for(var i = 0;i<ids.length;i++){
            render.scene.deleteGameObject(parseInt(ids[i]));
        }
        $("#gameObjectList option:selected").remove();
        if($("#gameObjectList option").length > 0){
            $("#gameObjectList option")[0].selected = true;
            $('#gameObjectList').trigger('change');
        }
        updateFrame();
    });
    
    $("#gameObjectList").change(function() {
        updateGameObject();
        gameObject = render.scene.getGameObject(parseInt($("#gameObjectList").val()));
        initGameObjectView();
    });
    
    $(".button").on("mouseover", function(event){
        $(this).css("background", "#FFA0DD");
    }).on("mouseout", function(event){
        $(this).css("background", "#DDA0DD");
    });

    $("#refresh").on("click",function(event){
        updateFrame();
    });
 
	$("#toon").on("click",function(event){
        if(!render)
	        return;

	    updateGameObject();
	    updateCamera();

	    render.begin();
	    render.draw();
		

		var canvas = new Engine.Canvas("main",render.width,render.height);
		render.depthMap(canvas);
		
    });
    
    $("#save").on("click",function(event){
        if(!render)
		{
			alert("Please select input file first");
		}
        window.requestFileSystem(window.TEMPORARY, 1024 * 1024,
        function(fs) {
            fs.root.getFile('output.ppm', {
                create: true
            },
            function(fileEntry) {
                fileEntry.createWriter(function(fileWriter) {
                    var builder;
			        try{
			        	builder = new WebKitBlobBuilder();
					}catch(e){
						try{
							builder = new MozBlobBuilder();
						}catch(e){
							alert("Your browser does not support HTML5 File API\nPlease use Chrome, Safari or FireFox");
							return;
						}
					}
					render.flush2file(builder);
			        var blob = builder.getBlob();

			        fileWriter.onwriteend = function() {
			            location.href = fileEntry.toURL();
			        };
                    
                    fileWriter.write(blob);
                });
            });
        });
    });
}



